How to load a local image to gpt4 您所在的位置:网站首页 Base64 Image Example How to load a local image to gpt4

How to load a local image to gpt4

2024-06-26 08:35| 来源: 网络整理| 查看: 265

import os

This code is for v1 of the openai package: openai · PyPI pip install openai pip install requests

from openai import OpenAI import base64 import requests

my_api_key = os.environ[“OPENAI_API_KEY”]

Function to encode the image

def encode_image(image_path): with open(image_path, “rb”) as image_file: return base64.b64encode(image_file.read()).decode(‘utf-8’)

Path to your image

image_path = “.\SourceImages\some_text.jpg”

Getting the base64 string

base64_image = encode_image(image_path)

Loads a local image file and OCRs it. https://platform.openai.com/docs/guides/vision

headers = { “Content-Type”: “application/json”, “Authorization”: f"Bearer {my_api_key}" }

payload = { “model”: “gpt-4-vision-preview”, “messages”: [ { “role”: “user”, “content”: [ { “type”: “text”, “text”: “What’s in this image?” }, { “type”: “image_url”, “image_url”: { “url”: f"data:image/jpeg;base64,{base64_image}" } } ] } ], “max_tokens”: 300 }

try:

response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload) print(response.json())

except Exception as ex: print(“Exception:”, ex)



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有